//
//  WebViewHandlerProtocool.swift
//  
//
//  Created by tank on 2021/12/4.
//

import Foundation
import WebKit

protocol WebViewHandlerProtocol: AnyObject {

    static var id: String { get }

    func handler(_ handler: WebViewHandlerProtocol, webView: WKWebViewEx?, frameInfo: WKFrameInfo, params: Any?)
}

extension WebViewHandlerProtocol {

    func runCallback(webView: WKWebViewEx, callback: String, uuid: String,
                     code: Int, message: String,
                     paramsDic: [String: Any],
                     completion: ((Any?, Error?) -> Void)? = nil) {

        let callbackParams = String(format: "('%@', %d, '%@')", uuid, code, message)

        if let callbackJS = paramsDic[callback] as? String {
            webView.evaluateJavaScript(callbackJS + callbackParams, completionHandler: completion)
        }

        if let complete = paramsDic["complete"] as? String {
            webView.evaluateJavaScript(complete + callbackParams, completionHandler: completion)
        }
    }
}
